<?php
/**
 * vim: et ts=4 sts=4 sw=4
 *
 * 加载一个PHP文件。并提供实例化
 *
 *
 * @author	Wang Penghai <china_php@hotmail.com>
 * @copyright 2007 5e6d Corporation.
 * @version   $Id: common.php 29 2009-03-10 14:30:18Z wph $
 */
class pf_load{


	/**
	 * 加载类，并初始化
	 */
	public static function init($file_name = '')
	{
		static $_instance = array();
		$key = md5($file_name);
		if (isset($_instance[$key]))
		{
			return $_instance[$key];
		} 

		self::load($file_name);
		return $_instance[$key] = new $file_name;
	}
	/**
	 * 加载model
	 *
	 */
	public static function load($file_name)
	{
		static $_file_list = array();
		$key = md5($file_name);
		if (isset($_file_list[$key]))
		{
			return;
		}

		$_file_list[$key] = 1;
		$file_path = APP_PATH . str_replace('_', DIRECTORY_SEPARATOR, $file_name) . '.php';
		if (!is_file($file_path))
		{
			die("load fiel fail : '$file_name' is not exist!");
		}
		include_once $file_path; 
	}
	/**
	 * 获取lib 的实例化对象
	 * 说明：不支持类初始化传参数。
	 *
	 * @param string $lib_name lib路径下的类名
	 * @param string $sub_dir 子目录。
	 *
	 * @return obj 
	 */
	public static function lib($lib_name, $sub_dir='')
	{
		static $lib_instance = array();
		if (isset($lib_instance[$lib_name]))
		{
			return $lib_instance[$lib_name];
		} 

		self::include_lib($lib_name, $sub_dir);

		$lib_instance[$lib_name] = new $lib_name;
		return $lib_instance[$lib_name];
	}

	/**
	 * 加载lib 类库
	 *
	 */
	public static function include_lib($lib_name, $sub_dir = '')
	{
		static $_lib_list = array();
		if (isset($_lib_list[$lib_name]))
		{
			return;
		}

		$_lib_list[$lib_name] = 1;
		if ($sub_dir !== '')
		{
			$sub_dir .= DIRECTORY_SEPARATOR;
		}
		$lib_file = LIB_PATH . $sub_dir . $lib_name . '.php';
		if (!is_file($lib_file))
		{
			die("lib file : '$lib_file' is not exist!");
		}
		include_once $lib_file; 
	}

	/**
	 * 获取db 的实例化对象
	 * 说明：不支持类初始化传参数。
	 *
	 * @param string $lib_name lib路径下的类名
	 * @param string $sub_dir 子目录。
	 *
	 * @return obj 
	 */
	public static function db($db_name, $sub_dir='')
	{
		static $db_instance = array();
		if (isset($db_instance[$db_name]))
		{
			return $db_instance[$db_name];
		} 

		self::include_db($db_name, $sub_dir);

		$db_instance[$db_name] = new $db_name;
		return $db_instance[$db_name];
	}

	/**
	 * 加载db 类库
	 *
	 */
	public static function include_db($db_name, $sub_dir = '')
	{
		static $_db_list = array();
		if (isset($_db_list[$db_name]))
		{
			return;
		}

		$_db_list[$db_name] = 1;
		if ($sub_dir !== '')
		{
			$sub_dir .= DIRECTORY_SEPARATOR;
		}
		$db_file = DB_DRIVER_PATH . $sub_dir . $db_name . '.php';
		if (!is_file($db_file))
		{
			die("db file : '$db_file' is not exist!");
		}
		include_once $db_file; 
	}

}

?>
